//    Copyright (C) Kherty.  All rights reserved.
using System;
using OpenLS.Core.Serialization;

namespace OpenLS.Spreadsheet
{
    public class DataBarFormattingRule : ConditionalFormattingRule
    {
        internal DataBarFormattingRule()
        {
            DataBar = new DataBar();
        }
        internal override ConditionalFormattingRule Clone()
        {
            var result = (DataBarFormattingRule) MemberwiseClone();
            result.DataBar = DataBar.Clone();
            return result;
        }

        internal DataBar DataBar { get; set; }
        internal override void ReadInner(ReadContext c)
        {
            DataBar = c.ReadOptionalElement<DataBar>("dataBar");

        }
        internal override void WriteInner(WriteContext c)
        {
            c.WriteOptionalElement(DataBar);
        }

        public DataBarFormattingRule(SpreadsheetColor color): this()
        {
            DataBar.Color = color;
        }
        internal DataBarFormattingRule (DataBar dataBar)
        {
            this.DataBar = dataBar;
        }
        public SpreadsheetColor Color{get{ return DataBar.Color;}}
        internal override ConditionalFormattingType Type
        {
            get { return ConditionalFormattingType.DataBar; }
        }
        internal override void ApplyRange(Range range)
        {
            maxValue = double.MinValue;
            minValue = double.MaxValue;
            foreach (Cell cell in range.GetNonEmptyCells())
            {
                object value = cell.Value;
                if (value is double)
                {
                    var d = (double) value;
                    maxValue = Math.Max(maxValue, d);
                    minValue = Math.Min(minValue, d);
                }
            }
            deltaValue = maxValue - minValue;
        }
        private double maxValue;
        private double minValue;
        private double deltaValue;
        internal override bool Apply(Cell cell)
        {
            object value = cell.Value;
            if (value is double)
            {
                var d = (double) value;
                double dataBarValue;
                if (deltaValue == 0)
                    dataBarValue = 0.5;
                else
                    dataBarValue = (d - minValue) / deltaValue;
                cell.DataBar = new DataBarInformation(dataBarValue, DataBar.Color, DataBar.MinimumLength, DataBar.MaximumLength);
            }
            return true;
        }
    }
}
